package jnpf.job;

import com.alibaba.fastjson.JSONObject;
import jnpf.base.UserInfo;
import jnpf.engine.model.flowmessage.FlowMsgModel;
import jnpf.engine.model.flowtask.WorkJobModel;
import jnpf.util.JsonUtil;
import jnpf.util.RedisUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 流程定时器工具类
 *
 * @author JNPF开发平台组
 * @version V3.3.0 flowable
 * @copyright 引迈信息技术有限公司
 * @date 2022/6/2 9:04
 */
public class WorkJobUtil {
    /**
     * 缓存key
     */
    public static final String REDIS_KEY = "idgenerator_WorkJobNew";

    /**
     * 将数据放入缓存
     *
     * @param
     * @return
     * @copyright 引迈信息技术有限公司
     * @date 2022/6/2
     */
    public static void insertRedis(WorkJobModel workJobModel, RedisUtil redisUtil) {
        JSONObject json = new JSONObject();
        json.put("taskId", workJobModel.getTaskId());
        json.put("flowMsgModel", JsonUtil.getObjectToString(workJobModel.getFlowMsgModel()));
        json.put("userInfo", JsonUtil.getObjectToString(workJobModel.getUserInfo()));
        redisUtil.insertHash(REDIS_KEY, workJobModel.getTaskId(), json.toJSONString());
    }

    /**
     * 定时器取用数据调用创建方法
     *
     * @param
     * @return
     * @copyright 引迈信息技术有限公司
     * @date 2022/6/2
     */
    public static List<WorkJobModel> getListRedis(RedisUtil redisUtil) {
        List<WorkJobModel> list = new ArrayList<>();
        if (redisUtil.exists(REDIS_KEY)) {
            Map<String, Object> map = redisUtil.getMap(REDIS_KEY);
            for (Object object : map.keySet()) {
                if (map.get(object) instanceof String) {
                    Map<String, Object> jsonMap = JsonUtil.stringToMap(String.valueOf(map.get(object)));
                    String taskId = jsonMap.get("taskId").toString();
                    FlowMsgModel flowMsgModel = JsonUtil.getJsonToBean(jsonMap.get("flowMsgModel").toString(), FlowMsgModel.class);
                    UserInfo userInfo = JsonUtil.getJsonToBean(jsonMap.get("userInfo").toString(), UserInfo.class);
                    list.add(new WorkJobModel(taskId, flowMsgModel, userInfo));
                }
            }
        }
        return list;
    }
}
